<?php

/**
 * @file IndexController
 * @author garypradoruiz <garypradoruiz@gmail.com>
 * @link mailto:garypradoruiz@gmail.com
 * @copyleft 2012 garypradoruiz
 * @license GPL
 * @version 1
 */
class Orden_IndexController extends Zend_Controller_Action {
    /*
     * status orden
     */

    protected $_PENDING = 0;
    protected $_PROGRESS = 1;
    protected $_PENDING_CLIENT = 2;
    protected $_CHANGES = 3;
    protected $_DENY = 4;
    protected $_APPROVED = 5;
    protected $_COMMITED = 6;
    protected $_SEND_EMAIL_NEW_ORDER = 0;
    protected $_SEND_EMAIL_CHANGE_ORDER = 1;
    protected $_SEND_EMAIL_DENY_ORDER = 2;

    /*
     * Function that only show orders client logued
     */

    public function indexAction() { // poner el cliente tambien
        $ordenDb = new Orden_Model_DbTable_Orden();

        $auth = Zend_Auth::getInstance();
        $iduser = $auth->getIdentity()->id;
        $idClient = $auth->getIdentity()->client_departament;

        $select = $ordenDb->select()->setIntegrityCheck(false)
                        ->from(array('o' => 'orden'), array('id', 'code', 'title', 'create_date_orden' => 'create_date', 'end_date', 'status'))//->where('o.deleted=?', 0)
                        ->join(array('ou' => 'orden_user'), 'o.id = ou.id_orden')
                        ->join(array('cl' => 'client'), 'cl.id = ou.id_client')->where('ou.id_client=?', $idClient)->group('o.id');
        //->join(array('u' => 'user'), 'u.id = ou.id_user')->where('u.id=?', $iduser)

        $result = $ordenDb->fetchAll($select);
        $this->view->ordenes_user = $result;
    }

    /*
     * Add orden, can be add user client or admin agency
     */

    public function addOrdenAction() { // si o si tenemos que agregar el cliente
        $ordenDb = new Orden_Model_DbTable_Orden();

        // get user logued
        $auth = Zend_Auth::getInstance();
        $iduser = $auth->getIdentity()->id;

        if ($this->getRequest()->isPost()) {
            $data = $this->_request->getParams();

            $dataOrden = array(
                'title' => $data['title'],
                'description' => $data['description'],
                'status' => $this->_PENDING,
                'create_date' => date('Y-m-d H:i:s', strtotime($data['create_date'])),
                'end_date' => date('Y-m-d', strtotime($data['end_date']))
            );
            $idOrden = $ordenDb->insert($dataOrden);

            if ($idOrden != 0) {
                // Registry orden user
                $ordenUser = new Orden_Model_DbTable_OrdenUser();
                $ordenUser->insert(array('id_orden' => $idOrden, 'id_user' => $iduser, 'id_client' => $auth->getIdentity()->client_departament));


                // Registry Orden Departament.
                $ordenDep = new Orden_Model_DbTable_OrdenDepartament();
                foreach ($data['checkDepartament'] as $dep) {
                    $dataOrdenDep = array('id_orden' => $idOrden, 'id_departament' => $dep);
                    $ordenDep->insert($dataOrdenDep);
                }

                //Registry Orden Jobs
                $ordenJob = new Orden_Model_DbTable_OrdenJob();
                for ($index = 1; $index <= $data['num_job']; $index++) {
                    $dataJob = array('id_orden' => $idOrden,
                        'name' => $data['name' . $index],
                        'detail' => $data['detail' . $index],
                        'end_date_client' => $data['date' . $index],
                        'status' => $this->_PENDING,
                        'end_date_client' => date('Y-m-d H:i:s', strtotime($data['date' . $index]))
                    );
                    $ordenJob->insert($dataJob);
                }

                //change from attachment-temp to attachment table
                $attachmentTemp = new Attachment_Model_DbTable_AttachmentTemp();
                $attachment = new Attachment_Model_DbTable_Attachment();
                $resultAttachTemp = $attachmentTemp->fetchAll("code = '" . $data['code_attachment'] . "'");
                foreach ($resultAttachTemp as $value) {
                    $dataAttach = array(
                        'name_original' => $value->name_original,
                        'name_saved' => $value->name_saved,
                        'description' => $value->description,
                        'extension' => $value->extension,
                        'content_type' => $value->content_type,
                        'create_date' => $value->create_date,
                        'status' => 0,
                        'id_order' => $idOrden,
                    );
                    $attachment->insert($dataAttach);
                }
                $attachmentTemp->delete("code = '" . $data['code_attachment'] . "'");

                $where = $ordenDb->getAdapter()->quoteInto('id=?', $idOrden);
                $ordenDb->update(array('code' => 'XAVR' . $idOrden), $where);

                $sendEmail = new Amz_Resource_SendEmail();
                $sendEmail->sendEmail($idOrden, 'NUEVA_ORDEN_CLIENTE');

                $this->_helper->FlashMessenger()
                        ->setNamespace('success')
                        ->addMessage('Orden Pendiente. Un mensaje de confirmaci&oacute;n ha sido 
                                      enviado a su correo y una copia a los 
                                      encargados de agencia.  Codigo de Orden: ' . 'XAVR' . $idOrden);
                if ($auth->getIdentity()->type == 'DEPARTAMENT')
                    $this->_helper->redirector->gotoUrlAndExit('/orden/orden/index/');
                else
                    $this->_helper->redirector->gotoUrlAndExit('/orden/index/index/');
            }
        } else {
            // Get all Departament or Agency
            $dpDB = new Departament_Model_DbTable_Departament();
            $select = $dpDB->select()->where('deleted=?', 0);
            $resultDep = $dpDB->fetchAll($select);
            $this->view->departaments = $resultDep;

            // Get all type jobs departament
            $dpJobDB = new Departament_Model_DbTable_DepartamentJob();
            $all_job_departament = $dpJobDB->fetchAll();
            $this->view->typejobs = $all_job_departament;

            // last insert id 
            $this->view->codeRand = $this->createRandomCode();

            $intDia = date("w");
            $hora = date("H");
            if ($intDia == 5 || $intDia == 6 || $intDia == 0) {
                if ($hora >= 17 && $intDia == 5) { // es viernes despues de las 17 para el lunes
                    $dayCorrect = mktime(8, 30, 0, date("m"), date("d") + 3, date("Y"));
                } else {
                    if ($intDia == 6) // es sabado
                        $dayCorrect = mktime(8, 30, 0, date("m"), date("d") + 2, date("Y"));
                    else // es domingo
                        $dayCorrect = mktime(8, 30, 0, date("m"), date("d") + 1, date("Y"));
                }
            } else {
                if ($intDia >= 1 && $intDia <= 4) { //es de lunes a jueves
                    if ($hora >= 1 && $hora <= 19) { //hora correcta orden para el dia actual
                        $dayCorrect = mktime(date("H"), date("i"), date("s"), date("m"), date("d"), date("Y"));
                    } else { //orden para el sgte dia
                        $dayCorrect = mktime(8, 30, 0, date("m"), date("d") + 1, date("Y"));
                    }
                }
            }
            $this->view->date_create = date('d-m-Y H:i:s', $dayCorrect);
        }
    }

    /*
     * Detail of orden only ordenes of a user client
     * also change status and add comment to orden
     */

    public function viewDetailOrdenAction() {
        $id = $this->_request->getParam('id', 0);
        $ordenDb = new Orden_Model_DbTable_Orden();
        $messageDb = new Orden_Model_DbTable_OrdenMessage();
        $auth = Zend_Auth::getInstance();
        $iduser = $auth->getIdentity()->id;

        if ($this->_request->isPost()) {
            $data = $this->_request->getParams();
            $ordenDb->update(array('status' => $data['status']), 'id=' . $data['id_orden']);
            $messageDb->insert(array('message' => $data['message'], 'id_orden' => $data['id_orden'], 'id_user' => $iduser));
            switch ($data['status']) {
                case 2:
                    $sendEmail = new Amz_Resource_SendEmail(); //Amz_Resource_SendEmail();
                    $sendEmail->sendEmail($id, 'ORDEN_CLIENT_REVIEW'); /// pendiente con cliente...
                    break;
                case 3:
                    $sendEmail = new Amz_Resource_SendEmail(); //Amz_Resource_SendEmail();
                    $sendEmail->sendEmail($id, 'ORDEN_CLIENT_REVISED'); /// cambios
                    break;
                case 5:
                    $sendEmail = new Amz_Resource_SendEmail(); //Amz_Resource_SendEmail();
                    $sendEmail->sendEmail($id, 'ORDEN_CLIENT_COMPLETE'); /// aprobado por el cliente
                    break;
            }

            // enviar email con el cambio de estado
            $this->_helper->FlashMessenger()
                    ->setNamespace('success')
                    ->addMessage('Usted realizo el cambio de estado en la orden XAVR' . $data['id_orden'] . ', se notificara a los involucrados para proceder.');
            $this->_redirect('/orden/index/index/id/' . $iduser);
        } else {
            $result = $ordenDb->fetchRow('id=' . $id);
            $this->view->details = $result;

            //trabajos a realizar dentro de la orden...
            $ordenDepJob = new Orden_Model_DbTable_OrdenJob();
            $selectDepJob = $ordenDb->select()->setIntegrityCheck(false)
                            ->from(array('odj' => 'orden_job'), array('*'))->where('id_orden=?', $id)->order('id asc');
            $dataOrdenDepJob = $ordenDepJob->fetchAll($selectDepJob);
            $this->view->dataJob = $dataOrdenDepJob;
            
            //User internals
            $ordenUserInternal = new Orden_Model_DbTable_OrdenUserInternal();
            $selectUserInternal = $ordenUserInternal->select()->setIntegrityCheck(false)
                                  ->from(array('ou' => 'orden_user_internal'), array('*'))->where('id_orden=?', $id)
                                  ->join(array('u'=>'user'), 'ou.id_user_internal = u.id', array('iduser'=>'id', 'nombre', 'apellidos'));
            $resultUserInternal = $ordenUserInternal->fetchAll($selectUserInternal);
            $this->view->resultUserInternal = $resultUserInternal;
        }
    }

    /*
     * Orden edited by user client  
     */

    public function editOrdenAction() {
        $ordenDb = new Orden_Model_DbTable_Orden();
        $ordenDep = new Orden_Model_DbTable_OrdenDepartament();
        $ordenDepJob = new Orden_Model_DbTable_OrdenJob();
        $attachment = new Attachment_Model_DbTable_Attachment();

        $auth = Zend_Auth::getInstance();
        $iduser = $auth->getIdentity()->id;

        if ($this->getRequest()->isPost()) {
            $flag = false;
            $data = $this->_request->getParams();

            $idOrden = $data['id'];
            $dataNew = array();
            $dataNew['status'] = $this->_PENDING;

            $dataNew['update_date'] = date('Y-m-d H:i:s');

            if ($data['check_brief']) {
                $dataNew['change_brief'] = $data['cambio_brief'];
                $flag = true;
            }
            if ($data['check_cambios']) {
                $dataNew['change_job'] = $data['trabajo_cambios'];
                $flag = true;
            }
            if ($data['check_date']) {
                $dataNew['new_date_limit'] = date('Y-m-d', strtotime($data['new_date_limit']));
                $flag = true;
            }
            // update Departament or Agency
            $ordenDep->delete('id_orden=' . $idOrden);
            foreach ($data['checkDepartament'] as $dep) {
                $dataOrdenDep = array('id_orden' => $idOrden, 'id_departament' => $dep);
                $ordenDep->insert($dataOrdenDep);
            }
            // update Departament Job or Agency Job
            $ordenDepJob->delete('id_orden=' . $idOrden);
            for ($index = 1; $index <= $data['num_job']; $index++) {
                $dataJob = array('id_orden' => $idOrden,
                    'name' => $data['name' . $index],
                    'detail' => $data['detail' . $index],
                    'end_date_client' => $data['date' . $index],
                    'status' => $this->_PENDING,
                    'end_date_client' => date('Y-m-d H:i:s', strtotime($data['date' . $index]))
                );
                $ordenDepJob->insert($dataJob);
            }

            //change from attachment-temp to attachment table
            $attachmentTemp = new Attachment_Model_DbTable_AttachmentTemp();
            $attachment = new Attachment_Model_DbTable_Attachment();
            $resultAttachTemp = $attachmentTemp->fetchAll("code = '" . $data['code_attachment'] . "'");
            foreach ($resultAttachTemp as $value) {
                $dataAttach = array(
                    'name_original' => $value->name_original,
                    'name_saved' => $value->name_saved,
                    'description' => $value->description,
                    'extension' => $value->extension,
                    'content_type' => $value->content_type,
                    'create_date' => $value->create_date,
                    'status' => 0,
                    'id_order' => $idOrden,
                );
                $attachment->insert($dataAttach);
            }
            $attachmentTemp->delete("code = '" . $data['code_attachment'] . "'");

            $ordenDb->update($dataNew, 'id=' . $idOrden);

            $sendEmail = new Amz_Resource_SendEmail(); //Amz_Resource_SendEmail();
            $sendEmail->sendEmail($idOrden, 'CLIENT_EDIT_ORDEN'); //  el cliente edito la orden

            $this->_helper->FlashMessenger()
                    ->setNamespace('success')
                    ->addMessage('Orden editada con exito. 
                                   Un mensaje de confirmaci&oacute;n ha 
                                   sido enviado a su correo y una copia a los 
                                   encargados de agencia.  
                                   Codigo de Orden: ' . 'XAVR' . $idOrden);
            $this->_helper->redirector->gotoUrlAndExit('/orden/index/view-detail-orden/id/' . $idOrden);
        } else {
            $id = $this->_request->getParam('id', 0);
            $select = $ordenDb->select()->where('id=?', $id)->where('deleted=?', 0);
            $result = $ordenDb->fetchRow($select);
            $this->view->orden = $result;

            $dataOrdenDep = $ordenDep->fetchAll('id_orden=' . $id);
            $this->view->dataOrdenDep = $dataOrdenDep;

            $dataOrdenDepJob = $ordenDepJob->fetchAll('id_orden=' . $id);
            $this->view->dataOrdenDepJob = $dataOrdenDepJob;

            $dataOrdenAttach = $attachment->fetchAll('id_order=' . $id);
            $this->view->dataOrdenAttach = $dataOrdenAttach;

            // Get all Departament or Agency
            $dpDB = new Departament_Model_DbTable_Departament();
            $select = $dpDB->select()->where('deleted=?', 0);
            $resultDep = $dpDB->fetchAll($select);
            $this->view->departaments = $resultDep;

            $this->view->codeRand = $this->createRandomCode();
        }
    }

    private function createRandomCode() {
        $chars = "abcdefghijkmnopqrstuvwxyz023456789";
        srand((double) microtime() * 1000000);
        $i = 0;
        $pass = '';
        while ($i <= 4) {
            $num = rand() % 33;
            $tmp = substr($chars, $num, 1);
            $pass = $pass . $tmp;
            $i++;
        }
        return $pass;
    }

    public function commentJobAction() {
        $this->_helper->layout()->disableLayout();
        $request = $this->getRequest();

        if ($request->isXmlHttpRequest()) {
            $id_orden = $request->getParam('id_orden', 0);
            $id_job = $request->getParam('id_job', 0);

            $this->view->name_job = $request->getParam('name', '');
            $this->view->id_orden = $id_orden;
            $this->view->id_job = $id_job;

            $ordenJobActivity = new Orden_Model_DbTable_OrdenJobActivity();
            $selectMessage = $ordenJobActivity->select()->setIntegrityCheck(false)
                    ->from(array('oda' => 'orden_job_activity'), array('id_orden', 'message', 'register_date', 'id_job', 'status'))
                    ->where('oda.id_orden=?', $id_orden)->where('id_job=?', $id_job)
                    ->join(array('u' => 'user'), 'u.id = oda.id_user');
            $this->view->resultJobActivity = $ordenJobActivity->fetchAll($selectMessage);
        }
    }

    public function saveCommentAction() {
        $this->_helper->layout()->disableLayout();
        $this->_helper->viewRenderer->setNoRender();

        $ordenJobAct = new Orden_Model_DbTable_OrdenJobActivity();
        $auth = Zend_Auth::getInstance();
        $iduser = $auth->getIdentity()->id;

        $request = $this->getRequest();
        if ($request->isXmlHttpRequest()) {
            $data = $request->getParams();

            $dataR = array(
                'id_orden' => $data['id_orden'],
                'id_job' => $data['id_job'],
                'id_user' => $iduser,
                'status' => $data['status'],
                'message' => $data['detail']
            );
            $x = $ordenJobAct->insert($dataR);
            if ($x != 0) {
                //update status orden departament job
                $ordenJob = new Orden_Model_DbTable_OrdenJob();
                $dataUpdate = array('status' => $data['status']);
                if ($data['status'] == $this->_APPROVED) {
                    $dataUpdate['end_date_agency'] = date('Y-m-d');
                }
                $ordenJob->update($dataUpdate, 'id_orden=' . $data['id_orden'] . ' and id=' . $data['id_job']);
                // send email status and comment 
                $this->sendMessageComment($data['id_orden'], $data['status']);

                $selectMessage = $ordenJobAct->select()->setIntegrityCheck(false)
                                ->from(array('oda' => 'orden_job_activity'), array('id_orden', 'message', 'register_date', 'id_job', 'status'))
                                ->where('oda.id=?', $x)->join(array('u' => 'user'), 'u.id = oda.id_user');
                $jsonData = Zend_Json::encode($ordenJobAct->fetchRow($selectMessage)->toArray());
                echo $jsonData;
            }
        }
    }

    private function sendMessageComment($idOrden=0, $status=0) {
        if ($idOrden != 0 && $status != 0) {
            switch ($status) {
                case 2:
                    $sendEmail = new Amz_Resource_SendEmail(); //Amz_Resource_SendEmail();
                    $sendEmail->sendEmail($idOrden, 'ORDEN_CLIENT_REVIEW'); /// pendiente con cliente...
                    break;
                case 3:
                    $sendEmail = new Amz_Resource_SendEmail(); //Amz_Resource_SendEmail();
                    $sendEmail->sendEmail($idOrden, 'ORDEN_CLIENT_REVISED'); /// cambios
                    break;
                case 5:
                    $sendEmail = new Amz_Resource_SendEmail(); //Amz_Resource_SendEmail();
                    $sendEmail->sendEmail($idOrden, 'ORDEN_CLIENT_COMPLETE'); /// aprobado por el cliente
                    break;
            }
        }
    }

    public function getUsersInternalAction() {
        $request = $this->getRequest();

        $this->_helper->layout()->disableLayout();
        $this->_helper->viewRenderer->setNoRender();

        $userDB = new User_Model_DbTable_User();

        if ($request->isXmlHttpRequest()) {

            $users = $userDB->fetchAll('type="CLIENT-INTERNAL" and client_departament=1 and estado=1');
            $items = array();
            foreach ($users as $u) {
                $items[$u->nombre . ' ' . $u->apellidos] = $u->id;
            }

            $q = strtolower($request->getParam("q"));
            if (!$q)
                return;

            foreach ($items as $key => $value) {
                if (strpos(strtolower($key), $q) !== false) {
                    //echo htmlspecialchars("$key|$value\n");
                    //echo strip_tags("$key|$value\n");
                    $results[] = array($key, $value);
                }
            }

            $jsonData = Zend_Json::encode($results);
            echo $jsonData;
        }
    }

    public function addCopyUsersAction() {
        $request = $this->getRequest();

        $this->_helper->layout()->disableLayout();
        $this->_helper->viewRenderer->setNoRender();

        $ordenUserInternal = new Orden_Model_DbTable_OrdenUserInternal();
        $userDB = new User_Model_DbTable_User();

        if ($request->isXmlHttpRequest()) {
            $users_str = $request->getParam('users');
            $id_orden = $request->getParam('orden_id');
            $email = $request->getParam('email');
            $users = explode(",", $users_str);

            foreach ($users as $us) {
                if ($us != '' && $us != null) {
                    $userRow = $userDB->fetchRow('id=' . $us);
                    //verificacion para no insertar de nuevo.
                    $rowInternal = $ordenUserInternal->fetchRow('id_user_internal=' . $us. ' and id_orden='.$id_orden);
                    if($rowInternal == null)
                        $ordenUserInternal->insert(array('id_orden' => $id_orden, 'id_user_internal' => $us, 'id_client' => $userRow->client_departament));
                    //Send email of copy detail
                    $sendEmail = new Amz_Resource_SendEmailCopyUser();
                    $sendEmail->sendEmail($id_orden, $users, $email ,'DETALLE_ORDEN_USER_INTERNAL'); //$id_orden = 0, $users = array(), $type=''
                }
            }
        }
    }
    
    public function deleteUserInternalAction() {
        $request = $this->getRequest();

        $this->_helper->layout()->disableLayout();
        $this->_helper->viewRenderer->setNoRender();

        $ordenUserInternal = new Orden_Model_DbTable_OrdenUserInternal();
        
        if ($request->isXmlHttpRequest()) {
            $userInternal = $request->getParam('id');
            $idorden = $request->getParam('idorden');
            $userI = $ordenUserInternal->fetchRow('id_user_internal='.$userInternal.' and id_orden='.$idorden);
            if($userI != null)
                $ordenUserInternal->delete('id_user_internal='.$userInternal.' and id_orden='.$idorden);
            echo 'eliminado';
        }
    }
}

?>